<template>
    <!-- 老评论系统：直播、秀场页 -->
    <div>
        <div :class='{"edit-component-container":!onTop,"edit-component-container-top":onTop}'>
            <div>{{testinfo}}</div>
            <div class="edit-component-face">
                <img  v-lazy="{src:authUserInfo.face,error: errimg, loading:errimg}" />
            </div>
            <div class="edit-component-box">
                <div class="edit-component-box-img" v-show="!is_edit">
                    <img src="../assets/images/pencil.png"/>
                </div>
                <div class="edit-component-box-txt">
                <textarea placeholder="我也要说两句" name="msg" @focus="msgAct(true)" @blur="msgAct(false)" :rows="rows"
                          v-model="msg"></textarea>
                </div>
                <div class="edit-component-box-btn" v-show="is_edit" @click="sendMsg();">发表</div>
                <div class="clearBoth"></div>
            </div>
            <div class="clearBoth"></div>
        </div>
        <ul class="remark-old-component-list" v-if="!hasNoComment">
            <li class="remark-old-component-item" v-for="(item,index) in info">
                <div class="remark-old-component-face">
                    <img v-lazy="{src:item.UserPic,error: errimg, loading:errimg}" :key='item.UserPic'/>
                </div>
                <div class="remark-old-component-info">
                    <div class="remark-old-component-title">
                        <a href="Javascript:;">{{item.NickName}}</a>
                        <span>&nbsp;&nbsp;{{item.SendTimeString}}</span>
                    </div>
                    <div class="remark-old-component-content">{{item.Content}}</div>
                </div>
                <div class="clearBoth"></div>
            </li>
        </ul>
        <div class="hall-component-blank" v-if="hasNoComment">
            <img v-lazy="defaultimg"/>
        </div>

        <!--<div class="edit-component-takeup"></div>-->
    </div>
</template>

<script>
    import qs from "querystring"
    import "../assets/libs/jquery.signalR-2.2.0.js"
    import "../assets/libs/interaction.js"
    //    import "../assets/libs/hubs.js"

    export default {
        props: {
            params: {
                type: Object,
                default: function () {
                    return {
                        businessType: "",
                        activityId: "",   // 177555
                        roleType: "",
                        programId: "",    // 40288db463f2ba5e0163f713841302aa
                        preChatId: ""
                    };
                }
            },
            reportData: {
                type: Object,
                default: function () {
                    return {};
                }
            },
            onTop: {
                type: Boolean,
                default: false
            }
        },
        data: function () {
            return {
                defaultimg:require("../assets/images/nocomment.png"),
                errimg: require("../assets/images/user.png"),
                rows: 1,
                is_edit: false,
                msg: "",    // 用户发送的消息

                info: [],
                // 用户信息接口
                authUrl: location.protocol + process.env.VUE_APP_UC_URL,
                authUserInfo: {
                    id: "",
                    nickname: "",
                    username: "",
                    face: ""
                },
                access_token: this.GetCookie("access_token"),
                openid: this.GetCookie("openid"),
                chatUrl: "",        // 获取边看边聊数据接口
                signalrStatus: 0,   // 连接状态
                testinfo: "",
//                reportdata: {},     // 上报用户行为的数据
                messageArray: [],   // 接收用户发送消息的数组
                hasNoComment: false,
            }
        },
        beforeCreate: function () {

        },
        mounted: async function () {
            if(this.$route.name=="Live"){
                if($(".fixedBottom").is(':hidden')){
                    $(".edit-component-container").css("bottom","0");
                    $(".edit-takeup").css("height","3.8rem");
                    $("#live_hall_container").css("padding-bottom","0");
                }
            }
            $(".hall-component-blank img").on('click',function(e){

                e.peventDefalut();

            })
            //this.access_token = this.getUrlParam("access_token");
            // this.openid = this.getUrlParam("openid");

            // 获取参数
            // console.log(JSON.stringify(this.params, undefined, 2));
            this.chatUrl = "/Chat/GetMoreHistoryChatsJsonp?" + qs.stringify(this.params);
            //console.log(this.chatUrl);
            this.getHistoryMsg();   // 获取历史消息

            // 引入资源
            let that = this;
            let head = document.head || (document.getElementBytagName("head")[0] || document.documentElement);
            let script = document.createElement("script");
            script.onload = function () {
                that.getComment();
            };
            script.onerror = function () {
                console.log("error");
            };
            script.async = false;
            script.type = "text/javascript";
            script.src = location.protocol + process.env.VUE_APP_COMMONT_URL + "/signalr/hubs";
            head.appendChild(script);

            // 自动建立连接
//            await this.getComment();    // By 汪凤杰

//            const s = document.createElement("script");
//            s.type = "text/javascript";
//            s.src = "http://210.51.168.204:8089/signalr/hubs";
//            document.body.appendChild(s);
        },
        methods: {
            msgAct: function (state) {
                let that = this;
                that.is_edit = state;
                if (that.is_edit) {
                    that.rows = 3;
                    let userCoo = that.GetCookie("YF_USER");
                    // alert(that.access_token);
                    if (userCoo == '' || userCoo == null) {
                        // 用户未登录，跳转登陆页
                        if (that.access_token == '' || that.openid == '' || that.access_token == null || that.openid == null) {
                          /*  var r=confirm("登录评论需刷新页面，确定登录并评论吗？");
                            if(r==false){
                                document.getElementsByTagName("textarea")[0].blur();
                                return false;
                            }else if(r==true){
                                // 用户未登录，跳转登陆页
                                that.openAuthorizePage();
                            }*/



                            that.$dialog.confirm('登录评论需刷新页面，确定登录并评论吗？',{
                                okText: '确定',  // 本地化确认按钮文字提示内容
                                cancelText: '取消',  //本地化关闭按钮文字提示内容
                            })
                                .then(function () {
                                    // 点击确定执行
                                    document.getElementsByTagName("textarea")[0].blur();
                                    // 用户未登录，跳转登陆页
                                    that.openAuthorizePage();
                                })
                                .catch(function () {
                                    // 点击取消执行
                                    document.getElementsByTagName("textarea")[0].blur();
                                    return false;
                                });

                        } else {

                            if (that.access_token == 'update' || that.openid == 'update') {
                                if (that.getUrlParam("access_token") != null && that.getUrlParam("openid") != null) {
                                    that.access_token = that.getUrlParam("access_token");
                                    that.openid = that.getUrlParam("openid");
                                    that.SetCookie("access_token", that.getUrlParam("access_token"), 365);
                                    that.SetCookie("openid", that.getUrlParam("openid"), 365);
                                    that.getAuthorizeUserInfo(that.access_token, that.openid);
                                } else {
                                /*    var r=confirm("登录评论需刷新页面，确定登录并评论吗？");
                                    if(r==false){
                                        document.getElementsByTagName("textarea")[0].blur();
                                        return false;
                                    }else if(r==true){
                                        // 用户未登录，跳转登陆页
                                        that.openAuthorizePage();
                                    }*/


                                    that.$dialog.confirm('登录评论需刷新页面，确定登录并评论吗？',{
                                        okText: '确定',  // 本地化确认按钮文字提示内容
                                        cancelText: '取消',  //本地化关闭按钮文字提示内容
                                    })
                                        .then(function () {
                                            // 点击确定执行
                                            document.getElementsByTagName("textarea")[0].blur();
                                            // 用户未登录，跳转登陆页
                                            that.openAuthorizePage();
                                        })
                                        .catch(function () {
                                            // 点击取消执行
                                            document.getElementsByTagName("textarea")[0].blur();
                                            return false;
                                        });

                                }
                            } else {
                                that.getAuthorizeUserInfo(that.access_token, that.openid);
                            }
                            // 用户已登录：获取用户信息
                            //  that.getAuthorizeUserInfo(that.access_token, that.openid);
                        }
                    } else {
                        that.authUserInfo=JSON.parse(that.GetCookie("YF_USER"));
                    }
                } else {
                    that.rows = 1;
                }
            },

            // 获取边看边聊数据
            getComment: function () {
                let that = this;
                // 建立连接
                function getInteraction() {
                    let newUrl = location.protocol + process.env.VUE_APP_COMMONT_URL;
                    window.interaction.init(
                        newUrl.replace("http://", "").replace("https://", "").replace("/", ""),
                        true,
                        receiveCallback,
                        stateCallback
                    );
                    that.axios.get(
                        interbaseUrl + "setsail/external/externalService?service=getParameterList&params={keys:'control_comment_link'}"
                    ).then((response) => {
                        if (response.state == 1000 && response.data.data.rows[0] && response.data.data.rows[0].value == "true") {
                            let datesecon = new Date().getSeconds();
                            if (datesecon % 2 == 0) {
                                window.interaction.connect();
                            }
                        } else {
                            window.interaction.connect();
                        }
                    });
                }

                // 建立连接时，注册接收数据回调函数
                function receiveCallback(obj) {
                    // 参数obj为实时获取的消息，对其进行必要的格式转换
                    var newObj = {
                        Id: obj.Id,
                        ActivityId: obj.ActivityId,
                        RoleType: obj.roletype,
                        NickName: obj.nickname,
                        PrefixNickName: obj.prefixnickname,
                        Content: obj.content,
                        ClearContent: obj.clearcontent,
                        SendTime: obj.sendtime,
                        SendTimeString: obj.sendtimestring,
                        UserPic: obj.userpic,
                        MsgStatus: obj.msgstatus,
                        businessType: obj.businesstype,
                        Uid: obj.uid,
                        Channelid: obj.channelid,
                        Programid: obj.programid,
                        MsgType: obj.msgtype,
                        PassThrough: obj.passthrough,
                        ContentUrl: obj.contenturl,
                        ContentTitle: obj.contenttitle,
                        FlagVersion: obj.flagversion
                    };
                    that.hasNoComment==false;
                    if(that.onTop){
                        that.info.unshift(newObj);
                    }else{
                        that.info.push(newObj);
                        setTimeout(function(){
                            $("#my_video_window_bottom").scrollTop($("#live_chat_container").height());
                        },200);
                    }
//                    that.info = newObj.concat(that.info);
//                    console.log("---------------------------");
//                    console.log(JSON.stringify(that.info, undefined, 2));
//                    console.log("---------------------------");
                }

                // 建立连接时，注册signalr状态回调函数
                function stateCallback(stateobj) {
                    if (stateobj.statuscode === 10001) {        // 互动文字信道链接成功
                        if (that.signalrStatus !== 1) {
                            window.interaction.join({
                                businessType: that.params.businessType,
                                activityId: that.params.activityId,
                                roleType: 0,
                                programId: that.params.programId
                            });
                            sendArrayMsg(); // 将链接成功前所发送的消息现在发送
                        }
                        that.signalrStatus = 1;
                    } else if (stateobj.statuscode === 10002 || stateobj.statuscode === 10004) { // 互动文字信道链接失败/中断
                        that.signalrStatus = 0;
                        window.interaction.connect();
                    }
                }

                // 互动文字信道链接成功后，将链接成功前所发送的消息现在发送
                function sendArrayMsg() {
                    let messagelength = that.messageArray.length;
                    for (let k = 0; k < messagelength; k++) {
                        let messageobj = that.messageArray.pop();
                        window.interaction.sendinteractionmsg(messageobj);
                    }
                }

                // 页面加载完毕时，建立连接
                getInteraction();
            },


            // 获取历史消息：页面加载完毕时
            getHistoryMsg: function () {
                // let getUrl = chatUrl
                //     + "?businessType=" + that.params["contenttype"]
                //     + "&activityId=" + that.params["contentid"]
                //     + "&roleType=0&programid=" + that.params["programid"]
                //     + "&preChatId=" + that.params["prechatid"];
                let that = this;
                console.log(this.chatUrl);
                this.axios.get(this.chatUrl).then((response) => {
                    // 获取数据
                    let rData = response.data;
                    that.$emit("change2", rData.total);
                    if(that.onTop){
                        that.info = rData.data
                    }else{
                        if(rData.data.length==0){
                            that.hasNoComment=true;
                        }
                        that.info = rData.data.reverse();
                        setTimeout(function(){
                            $("#my_video_window_bottom").scrollTop($("#live_chat_container").height());
                        },200)
                    }

//                    alert(JSON.stringify(this.info));
//                    console.log("----------------------------");
//                   console.log(JSON.stringify(this.info, undefined, 2));
//                    console.log("----------------------------");
                });
            },

            // 发送消息
            sendMsg: function () {
                // alert(JSON.stringify(this.params));
                let that = this;
                let model = {
                    Id: "1",
                    ActivityId: that.params.activityId,
                    roletype: that.params.roleType,
                    nickname: that.authUserInfo.nickname ? that.authUserInfo.nickname : "a",
                    content: that.msg,
                    sendtime: new Date().Format("yyyy-MM-dd hh:mm"),
                    uid: that.authUserInfo.id ? that.authUserInfo.id : "a",
                    channelid: that.params.activityId,
                    contentid: that.params.programId,
                    userpic: that.authUserInfo.face,
                    businesstype: that.params.businessType,
                    msgtype: "1",
                    contenturl: that.params.contenturl,// 从节目数据中获取分享URL
                    contenttitle: that.params.contenttitle,// 从节目数据中获取分享标题
                    clearcontent: that.msg,
                    sendtimestring: new Date().Format("hh:mm"),
                    flagversion: "1"
                };
//                alert(JSON.stringify(model));
                // alert("要发送的评论数据：" + JSON.stringify(model));
             //   alert(this.signalrStatus === 1)
                if (this.signalrStatus === 1) {
                    // 互动文字信道链接成功时，直接调用发送消息sdk方法
                    window.interaction.sendinteractionmsg(model);

                    // 消息发送成功后的处理:头像、昵称、时间、评论内容
                  /*  alert("消息发送成功！");*/
                    let newCommentData = {
                        Id: model.Id,
                        ActivityId: model.ActivityId,
                        RoleType: model.roletype,
                        NickName: model.nickname,
                        PrefixNickName: model.nickname,
                        Content: model.content,
                        ClearContent: model.content,
                        SendTime: model.sendtime,
                        SendTimeString: model.sendtimestring,
                        UserPic: model.userpic,
                        MsgStatus: 1,
                        businessType: model.businesstype,
                        Uid: model.uid,
                        Channelid: model.channelid,
                        Programid: model.contentid,
                        MsgType: model.msgtype,
                        PassThrough: 0,
                        ContentUrl: model.contenturl,
                        ContentTitle: model.contenttitle,
                        FlagVersion: model.flagversion
                    };
//                    alert(JSON.stringify(that.info));
//                    alert(JSON.stringify(newCommentData));
                    that.hasNoComment==false;
                    // 发送者显示实时消息
                    if(that.onTop){
                        that.info.unshift(newCommentData);
                    }else{
                        that.info.push(newCommentData);
                        setTimeout(function(){
                            $("#my_video_window_bottom").scrollTop($("#live_chat_container").height());
                        },200)
                    }
//                    that.info = newCommentData.concat(that.info);
                    that.msg = "";
                    // 即时更新消息总数
                    that.$emit("change2", that.info.length);
                    // 上报用户行为
                    function doComment() {
                        let actionType = "comment";
                        that.reportData.uid = that.authUserInfo.id;
                        that.reportData.username = that.authUserInfo.nickname;
                        // console.log(JSON.stringify(that.reportdata, undefined, 2));
                        shareUrlReport(that.reportData, actionType);
                    }
                    doComment();
                } else {
                    // 互动文字信道链接不成功时，先存入messageArray数组中，等链接成功后再调用sdk发送，数组messageArray为页面定义的变量
                    that.messageArray.push(model);
//                    alert("通道连接失败：" + JSON.stringify(that.messageArray));
                }
            },

            // 跳转授权页面
            openAuthorizePage: function () {
                this.SetCookie("access_token", "update", 1 / 24 / 6);
                this.SetCookie("openid", "update", 1 / 24 / 6);
                let authUrl = this.authUrl + "v1/oauth2/web/otherAuthorize";
                let url = location.protocol + '//' + location.host + location.pathname;
                location.href = authUrl + "?redirect_uri=" + escape(url);
            },

            // 获取授权信息
            getAuthorizeUserInfo: function (access_token, openid) {
                //  alert(access_token+";"+openid);
                let that = this;
                let requestUrl = that.authUrl + "/user/info?access_token=" + access_token + "&openid=" + openid;
                // alert("access_token:" + access_token + ";openid:" + openid);

                that.axios.get(requestUrl).then((response) => {
                    let res = response.data;
                    if (res.code === 0) {
                        that.authUserInfo = res.user;
                        // alert("AuthUserInfo：" + JSON.stringify(that.authUserInfo));
                        that.SetCookie("YF_USER", JSON.stringify(res.user), 365);
                    } else {
                        console.error("获取用户信息失败：code=" +res.code);
                        if( res.code=42001){
                            this.ClearCookie("access_token");
                            this.ClearCookie("openid");
                            that.openAuthorizePage();
                        }
                    }
                });
            }
        }
    }
</script>

<style>
    .remark-old-component-list a,
    .remark-old-component-list a:link,
    .remark-old-component-list a:visited {
        color: #459AF5;
        text-decoration: none;
    }

    .remark-old-component-list {
        padding: 0;
        margin: 0 auto;
    }

    .remark-old-component-item {
        margin: 0.6rem auto;
        position: relative;
        padding-left: 40px;
    }

    .remark-old-component-face {
        width: 32px;
        position: absolute;
        left: 0;
        top: 5px;
    }

    .remark-old-component-face img {
        width: 32px;
        height: 32px;
        border-radius: 50%;
    }

    .remark-old-component-info {
        width: 100%;
    }

    .remark-old-component-title,
    .remark-old-component-content {
        line-height: 1.8rem;
    }

    .remark-old-component-title {
        font-size: 0.9rem;
        color: #999999;
    }

    .remark-old-component-content {
        font-size: 1.0rem;
        color: #666666;
    }

    .remark-old-component-foot {
        line-height: 2.8rem;
        font-size: 0.9rem;
        color: #666666;
    }

    .remark-old-component-has-reply {
        background-color: #EDEDED;
        border-radius: 0.55rem;
        padding: 0.1rem 0.3rem;
    }

    .remark-old-component-reply {
        font-size: 0.9rem;
        background-color: #F5F5F5;
        padding: 0.5rem;
    }

    .remark-old-component-reply-content {
        color: #444444;
    }

    .remark-old-component-reply-time {
        color: #999999;
    }

    /* 输入框部分 */
    /*.edit-component-takeup {*/
    /*width: 100%;*/
    /*height: 3.8rem;*/
    /*}*/
    .edit-component-container, .edit-component-container-top {
        width: 100%;
        min-height: 2.2rem;
        margin: 0 auto;
        padding: 1.2rem 0.6rem;
        box-sizing: border-box;
        background-color: #FFFFFF;
        /*border-top: 0.06rem solid #CCCCCC;*/
        /*border-bottom: 0.06rem solid #CCCCCC;*/
    }

    .edit-component-container {
        position: fixed;
        bottom: 0;
        left: 0;
        z-index: 10000;
        background: #fff;
    }

    .edit-component-face {
        width: 12%;
        float: left;
    }

    .edit-component-face img {
        display: block;
        height: 32px;
        border-radius: 100%;
    }

    .edit-component-box {
        width: 86%;
        float: right;
        border: 1px solid #E5E5E4;
        border-radius: 0.3rem;
        line-height: 1.9rem;
        background-color: #FAFAFA;
        color: #444444;
        overflow: hidden;
    }

    .edit-component-box-img {
        width: 12%;
        float: left;
        text-align: center;
    }

    .edit-component-box-img img {
        width: 1.0rem;
        vertical-align: middle;
    }

    .edit-component-box-txt {
        height: 1.9rem;
        line-height: 1.9rem;
        width: 81%;
        float: left;
    }

    .edit-component-box-txt textarea {
        border: none;
        background-color: #FAFAFA;
        width: 95%;
        font-size: 1rem;
        line-height: 1.9rem;
        padding: 0 0.4rem;
        resize:none;
        margin-top: 0.1rem;
    }

    .edit-component-box-btn {
        background-color: #E5E5E4;
        height: 5.7rem;
        line-height: 5.7rem;
        width: 18%;
        text-align: center;
        font-size: 0.9rem;
        float: right;
    }

    /* 没有评论时的默认样式 */
    .hall-component-blank {
        margin-top: 1.0rem;
    }

    .hall-component-blank img {
        display: block;
        width: 45%;
        margin:0 auto;
        pointer-events:none;
    }
</style>